package com.liang.three;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import utils.RabbitmqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: XIAOLIANG
 * Date: 2021/6/17
 * Time: 19:07
 * Description: 消息手动应答 消费比较快 2S 消费一个
 */
public class Work03 {

    public static final String QUEUE_NAME ="ack_queue" ;

    public static void main(String[] args) throws IOException, TimeoutException {

        Channel channel = RabbitmqUtil.getChannel();

        System.out.println("work03开始接受等待处理消息 等待时间短...");

//采用手动应答
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                try {
                    Thread.sleep(1000*1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("c1接受到的消息"+new String(message.getBody(), StandardCharsets.UTF_8));
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false); //手动应答 不批量应答
            }
        };

        //消息取消的回调代码
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                System.out.println(consumerTag+"消费者取消 消费 ");
            }
        };

//        channel.basicQos(1); 1表示不公平分发
        channel.basicQos(2);//表示 预取值 2条  预期值表示消息堆积在信道里
        channel.basicConsume(QUEUE_NAME,false,deliverCallback,cancelCallback);




    }


}